package libs

import (
	"devOpsApi/common/util"
	"github.com/kataras/iris/context"
	"github.com/patrickmn/go-cache"
	"sync"
	"time"
)

var CacheObj *cache.Cache

//初始化缓存配置 只能初始化一次
func InitCache() {
	var initOnce sync.Once
	initOnce.Do(func() {
		CacheObj = cache.New(30*time.Second, 10*time.Second)
	})
}

//设置缓存
func SetCacheDefault(cacheKey string, val interface{}, d time.Duration) {
	CacheObj.Set(cacheKey, val, d)
}

//设置缓存 中间件使用
func SetCache(ctx context.Context, val interface{}, d time.Duration) {
	cacheKey := GetCacheKey(ctx)
	CacheObj.Set(cacheKey, val, d)
}

//获取缓存
func GetCache(key string) (value interface{}, found bool) {
	value, found = CacheObj.Get(key)
	return
}

//获取缓存Key
func GetCacheKey(ctx context.Context) string {
	cacheKey := ctx.RemoteAddr() + ctx.Method() + ctx.Request().RequestURI + ctx.GetHeader("Authorization")
	cacheKey = util.BeeMd5(cacheKey)
	return cacheKey
}
